#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

int main()
{
    pid_t pid = fork();

    if (pid == -1)
    {
        // 创建子进程失败
        std::cerr << "failed to fork" << std::endl;
        return 1;
    }
    else if (pid == 0) // 子进程
    {
        // 子进程任务内容
        sleep(2); // 进程等待时间
        std::cout << "Child process: My PID is " << getpid() << std::endl;
        std::cout << "Child process: My parent's PID is " << getppid() << std::endl;
        //int count = 0;
        while (1)
        {
            // 打印子进程进程号信息。
            printf("The child  process is running ! childpid=%d fatherpid=%d \n", getpid(), getppid());
            sleep(2);
            // count++;
            // if (count == 5)
            // {
            //     // 当子进程运行5 次就退出
            //     printf("The child process will be exit !\n");
            //     exit(0); //**
            // }
        }
    }
    else // 父进程
    {
        std::cout << "Parent process: My PID is " << getpid() << std::endl;
        // sleep(3); // 等待子进程输出
        return 0; // 父进程立即退出，子进程变孤儿进程
    }

    return 0;
}
